﻿using Microsoft.EntityFrameworkCore;
using Store.IDAL;
using Store.Models;
using System;
using System.Linq;
using System.Threading.Tasks;

namespace Store.DAL
{
    public class BaseService<T> : IDAL.IBaseService<T> where T : Models.BaseEnity, new()
    {
        private readonly StoreDBContext _db;

        public BaseService(StoreDBContext db)
        {
            _db = db;
        }

        public async Task CreateAsync(T model, bool saved = true)
        {
            _db.Set<T>().Add(model);
            if (saved) await _db.SaveChangesAsync();
        }

        public void Dispose()
        {
            _db.Dispose();
        }

        public async Task EditAsync(T model, bool saved = true)
        {
            _db.Entry(model).State = EntityState.Modified;
            if (saved) await _db.SaveChangesAsync();
        }

        public IQueryable<T> GetAllAsync()
        {
            return _db.Set<T>().Where(m => !m.IsRemove).AsNoTracking();
        }

        public async Task<T> GetOneById(Guid id)
        {
            return await GetAllAsync().FirstAsync(m => m.Id == id);
        }

        public async Task RemoveAsync(T model, bool saved = true)
        {
            await RemoveAsync(model.Id, saved);
        }

        public async Task RemoveAsync(Guid id, bool saved = true)
        {
            _db.Entry(new T() { Id = id }).State = EntityState.Unchanged;
            if (saved) await _db.SaveChangesAsync();
        }

        public async Task Save()
        {
            await _db.SaveChangesAsync();
        }
    }
}
